package play.modules.facebook;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import play.exceptions.UnexpectedException;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Wrapper around session map
 * User: dallan
 */
public class Session implements Cloneable {
   SortedMap<String,String> data;

   public Session(String cookie) {
      Map<String,String[]> temp = Utils.parse_str(cookie);
      data = new TreeMap<String,String>();
      for(String key : temp.keySet()) {
         String[] values = temp.get(key);
         if (values.length > 1) {
            throw new UnexpectedException("Session with array-valued field");
         }
         data.put(key, values[0]);
      }
   }

   public Session(JsonElement json) {
      data = new TreeMap<String,String>();
      try {
         data.putAll(Utils.jsonToMap(json));
      }
      catch (JsonParseException e) {
         throw new UnexpectedException("Unexpected session: "+json.getAsString());
      }
   }

   public Session(String uid, String accessToken, String expires) {
      data = new TreeMap<String,String>();
      data.put("uid",uid);
      data.put("access_token", accessToken);
      data.put("expires", expires);
   }

   public Session clone() throws CloneNotSupportedException {
      Session clone = (Session)super.clone();
      clone.data = new TreeMap<String,String>();
      clone.data.putAll(data);
      return clone;
   }

   public String getUid() {
      return data.get("uid");
   }

   public String getAccessToken() {
      return data.get("access_token");
   }

   public String getBaseDomain() {
      return data.get("base_domain");
   }

   public String getExpires() {
      return data.get("expires");
   }

   public String getSignature() {
      return data.get("sig");
   }

   public void setSignature(String signature) {
      if (signature != null) {
         data.put("sig", signature);
      }
      else {
         data.remove("sig");
      }
   }

   public SortedMap<String,String> asSortedMap() {
      return data;
   }

   public String toJson() {
      return new Gson().toJson(data);
   }

   public String toString() {
      StringBuilder buf = new StringBuilder();
      for (String key : data.keySet()) {
         buf.append(key);
         buf.append("=");
         buf.append(data.get(key));
         buf.append("|");
      }
      return buf.toString();
   }
}
